<template>
  <div class="category-management">
    <div class="page-header">
      <h2>分类管理</h2>
      <p>管理停车场的分类信息</p>
    </div>

    <!-- 操作区域 -->
    <el-card class="action-card" shadow="never">
      <el-button type="primary" @click="handleAdd">
        <el-icon><Plus /></el-icon>
        新增分类
      </el-button>
    </el-card>

    <!-- 表格区域 -->
    <el-card class="table-card" shadow="never">
      <el-table
        v-loading="loading"
        :data="tableData"
        stripe
        style="width: 100%"
      >
        <el-table-column prop="id" label="ID" width="80" />
        <el-table-column prop="name" label="分类名称" min-width="150" />
        <el-table-column label="图标预览" width="100">
          <template #default="{ row }">
            <el-image
              v-if="row.icon_url"
              :src="row.icon_url"
              :preview-src-list="[row.icon_url]"
              style="width: 40px; height: 40px"
              fit="cover"
            />
            <span v-else class="no-icon">无图标</span>
          </template>
        </el-table-column>
        <el-table-column prop="sort_order" label="排序值" width="100" />
        <el-table-column label="创建时间" width="180">
          <template #default="{ row }">
            {{ formatDate(row.created_at) }}
          </template>
        </el-table-column>
        <el-table-column label="操作" width="150" fixed="right">
          <template #default="{ row }">
            <el-button
              type="primary"
              size="small"
              @click="handleEdit(row)"
            >
              编辑
            </el-button>
            <el-button
              type="danger"
              size="small"
              @click="handleDelete(row)"
            >
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-card>

    <!-- 新增/编辑对话框 -->
    <el-dialog
      v-model="dialogVisible"
      :title="dialogTitle"
      width="500px"
      @close="handleDialogClose"
    >
      <el-form
        ref="formRef"
        :model="formData"
        :rules="formRules"
        label-width="100px"
      >
        <el-form-item label="分类名称" prop="name">
          <el-input
            v-model="formData.name"
            placeholder="请输入分类名称"
            maxlength="50"
            show-word-limit
          />
        </el-form-item>
        <el-form-item label="图标URL" prop="icon_url">
          <el-input
            v-model="formData.icon_url"
            placeholder="请输入图标URL"
            type="textarea"
            :rows="2"
          />
        </el-form-item>
        <el-form-item label="排序值" prop="sort_order">
          <el-input-number
            v-model="formData.sort_order"
            :min="0"
            :max="9999"
            placeholder="排序值，越小越靠前"
            style="width: 100%"
          />
        </el-form-item>
      </el-form>

      <template #footer>
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleSubmit" :loading="submitLoading">
          确定
        </el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox, type FormInstance, type FormRules } from 'element-plus'
import { Plus } from '@element-plus/icons-vue'
import {
  getCategoriesList,
  createCategory,
  updateCategory,
  deleteCategory,
  type Category,
  type CreateCategoryData,
  type UpdateCategoryData
} from '@/api/category'

// 响应式数据
const loading = ref(false)
const tableData = ref<Category[]>([])
const dialogVisible = ref(false)
const dialogTitle = ref('')
const submitLoading = ref(false)
const isEdit = ref(false)
const editId = ref<number | null>(null)

// 表单引用和数据
const formRef = ref<FormInstance>()
const formData = reactive({
  name: '',
  icon_url: '',
  sort_order: 0
})

// 表单验证规则
const formRules: FormRules = {
  name: [
    { required: true, message: '请输入分类名称', trigger: 'blur' },
    { min: 1, max: 50, message: '分类名称长度在 1 到 50 个字符', trigger: 'blur' }
  ],
  sort_order: [
    { required: true, message: '请输入排序值', trigger: 'blur' },
    { type: 'number', min: 0, max: 9999, message: '排序值范围为 0-9999', trigger: 'blur' }
  ]
}

/**
 * 获取分类列表
 */
const fetchCategoriesList = async () => {
  try {
    loading.value = true
    const response = await getCategoriesList()

    if (response.success) {
      tableData.value = response.data
    } else {
      ElMessage.error(response.message || '获取分类列表失败')
    }
  } catch (error) {
    console.error('获取分类列表错误:', error)
    ElMessage.error('获取分类列表失败')
  } finally {
    loading.value = false
  }
}

/**
 * 新增分类
 */
const handleAdd = () => {
  isEdit.value = false
  editId.value = null
  dialogTitle.value = '新增分类'
  resetForm()
  dialogVisible.value = true
}

/**
 * 编辑分类
 */
const handleEdit = (row: Category) => {
  isEdit.value = true
  editId.value = row.id
  dialogTitle.value = '编辑分类'

  formData.name = row.name
  formData.icon_url = row.icon_url
  formData.sort_order = row.sort_order

  dialogVisible.value = true
}

/**
 * 删除分类
 */
const handleDelete = async (row: Category) => {
  try {
    await ElMessageBox.confirm(
      `确定要删除分类"${row.name}"吗？`,
      '删除确认',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )

    const response = await deleteCategory(row.id)

    if (response.success) {
      ElMessage.success('删除成功')
      fetchCategoriesList()
    } else {
      ElMessage.error(response.message || '删除失败')
    }
  } catch (error: any) {
    if (error !== 'cancel') {
      console.error('删除分类错误:', error)
      ElMessage.error('删除失败')
    }
  }
}

/**
 * 提交表单
 */
const handleSubmit = async () => {
  if (!formRef.value) return

  try {
    await formRef.value.validate()
    submitLoading.value = true

    const data = {
      name: formData.name.trim(),
      icon_url: formData.icon_url.trim(),
      sort_order: formData.sort_order
    }

    let response
    if (isEdit.value && editId.value) {
      response = await updateCategory(editId.value, data as UpdateCategoryData)
    } else {
      response = await createCategory(data as CreateCategoryData)
    }

    if (response.success) {
      ElMessage.success(isEdit.value ? '更新成功' : '创建成功')
      dialogVisible.value = false
      fetchCategoriesList()
    } else {
      ElMessage.error(response.message || '操作失败')
    }
  } catch (error) {
    console.error('提交表单错误:', error)
  } finally {
    submitLoading.value = false
  }
}

/**
 * 对话框关闭处理
 */
const handleDialogClose = () => {
  resetForm()
}

/**
 * 重置表单
 */
const resetForm = () => {
  formData.name = ''
  formData.icon_url = ''
  formData.sort_order = 0
  formRef.value?.clearValidate()
}

/**
 * 格式化日期
 */
const formatDate = (dateString: string) => {
  return new Date(dateString).toLocaleString('zh-CN')
}

// 组件挂载时获取数据
onMounted(() => {
  fetchCategoriesList()
})
</script>

<style scoped>
.category-management {
  padding: 20px;
}

.page-header {
  margin-bottom: 20px;
}

.page-header h2 {
  margin: 0 0 8px 0;
  color: #303133;
}

.page-header p {
  margin: 0;
  color: #909399;
  font-size: 14px;
}

.action-card {
  margin-bottom: 20px;
}

.table-card {
  margin-bottom: 20px;
}

.no-icon {
  color: #c0c4cc;
  font-size: 12px;
}
</style>
